package com.jy.rhin.domain.cda;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jy.framework.base.exception.BaseException;
import com.jy.rhin.RhinAggrApplication;
import com.jy.rhin.model.ClinicalDocumentData;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.StringWriter;
import java.util.Objects;

@Slf4j
@Service
public class CDACreator {

    public String create(ClinicalDocumentData clinicalDocumentData, String path) {
        try {
            JSONObject data = getData(clinicalDocumentData);
            //创建配置类
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
            String classpath = Objects.requireNonNull(this.getClass().getResource("/cda/templates/")).toURI().getPath();
            //设置模板路径
            ClassTemplateLoader loader = new ClassTemplateLoader(RhinAggrApplication.class, "/cda/templates");
            configuration.setTemplateLoader(loader);
            //设置字符集
            configuration.setDefaultEncoding("UTF-8");
            //加载模板
            Template template = configuration.getTemplate(path);
            StringWriter out = new StringWriter();
            template.process(data, out);
            return out.toString();
        } catch (Exception e) {
            log.error("生成CDA错误", e);
            throw new BaseException("生成CDA错误:\n" + e.toString());
        }
    }

    public JSONObject getData(ClinicalDocumentData clinicalDocumentData) {
        if (Objects.isNull(clinicalDocumentData)) {
            return new JSONObject();
        }
        JSONObject jsonObject = new JSONObject();
        Object value = JSON.toJSON(clinicalDocumentData);
        jsonObject.put("docData", value);
        return jsonObject;
    }

}
